package com.hxkcloud.patient.activitys;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.DisabilityKindAdapter;
import com.hxkcloud.patient.adapter.DoctorGroupAdapter;
import com.hxkcloud.patient.adapter.MainPageListAdapter;
import com.hxkcloud.patient.beans.DisabilityBean;
import com.hxkcloud.patient.beans.DisabilityListBean;
import com.hxkcloud.patient.beans.DoctorGroupBean;
import com.hxkcloud.patient.beans.DoctorPatientBean;
import com.hxkcloud.patient.beans.DoctorPatientGroupBean;
import com.hxkcloud.patient.beans.DoctorPatientListBean;
import com.hxkcloud.patient.beans.DoctorPatientResultBean;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.dborm.DoctorGroupDao;
import com.hxkcloud.patient.popup.CalendarClearPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.views.CircleImageView;

import java.util.ArrayList;
import java.util.List;

/**
 * ProjectName: YJHCuzhong
 * PackageName: com.yjhcloud.patient.activitys
 * Description:
 * Create by Ray.
 * Date: 2016/9/28 14:04
 */
public class MainPageActivity extends BaseActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener,MainPageListAdapter.ResultSelectedListener{

    private SwipeRefreshLayout swipeRefreshLayout;
    private ExpandableListView expandableListView;
    private MyExpandableListViewAdapter expandAdapter;

    private RecyclerView recyclerView;
    private MainPageListAdapter adapter;
    private List<DoctorPatientBean> patientListDatas;

    private List<DoctorPatientGroupBean> group_list;
    private List<List<DoctorPatientBean>> item_list;


    private TextView countTV;


    private LinearLayout ivgLayout;

    private LinearLayout groupLayout;
    private TextView groupTV;
    private ImageView groupIV;

    private LinearLayout disabilityLayout;
    private TextView disabilityTV;
    private ImageView disabilityIV;

    private LinearLayout timeLayout;
    private TextView timeTV;
    private ImageView timeIV;

    private CalendarClearPopWindow calendarView;

    private PopupWindow allPopup;//选择全部
    private ListView allListView;
    private DoctorGroupAdapter allAdapter;
    private View allWholeView;

    private PopupWindow kindPopup;//选择病种
    private ListView kindListView;
    private DisabilityKindAdapter kindAdapter;

    private View kindWholeView;

    private List<DoctorGroupBean> groupBeans;

    private ObjectResultBean<DisabilityListBean> disabilityResultBean;//残疾程度返回值

    private List<DisabilityBean> disabilityBeans;//残疾程度列表

    private ObjectResultBean<DoctorPatientResultBean> resultBean;//返回结果集

    private List<DoctorPatientGroupBean> patientGroupBeans;//分组列表
    private DoctorPatientListBean patientListBean;//非分组列表

    private String patientCount = "";//非分组人数

    private String groupIdSelected ="";//选中的groupId
    private String disabilitySelected="";//选中的残疾程度
    private String dateSelected = "";//选中的日期



    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_DOCTORPATIENTLIST_SUCCESS:
                dismisssLoading();
                if(msg.obj !=null){
                    resultBean = (ObjectResultBean<DoctorPatientResultBean>) msg.obj;
                    if(resultBean.getData().getFzList()!=null){
                        patientGroupBeans = resultBean.getData().getFzList();
                        group_list.clear();
                        item_list.clear();
                        if(patientGroupBeans!=null && patientGroupBeans.size()>0){
                            expandableListView.setVisibility(View.VISIBLE);
                            for(int i = 0;i<patientGroupBeans.size();i++){
                                group_list.add(patientGroupBeans.get(i));
                                item_list.add(patientGroupBeans.get(i).getPatients());
                            }
                            expandableListView.setAdapter(expandAdapter);
                            setListViewHeight(expandableListView);
                        }else{
                            expandableListView.setVisibility(View.GONE);
                        }
                    }
                    if(resultBean.getData().getFfzMap()!=null){
                        if(patientListDatas!=null&&patientListDatas.size()>0){
                            patientListDatas.clear();
                        }
                        patientListBean = resultBean.getData().getFfzMap();
                        patientCount = patientListBean.getPatientCount()+"";
                        countTV.setText(patientCount+getResources().getString(R.string.mainpage_text_person));
                        patientListDatas = patientListBean.getPatients();
                        if(patientListDatas!=null && patientListDatas.size()>0){
                            recyclerView.setVisibility(View.VISIBLE);
                            adapter = new MainPageListAdapter(this, patientListDatas,this, screenWidth);
                            recyclerView.setAdapter(adapter);
//                          adapter.setData(patientListDatas);
                        }else{
                            countTV.setText("0" + getResources().getString(R.string.mainpage_text_person));
                            recyclerView.setVisibility(View.GONE);
                        }

                    }

                }

                break;
            case MessageCode.NETWORKCODE_DOCTORPATIENTLIST_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;


            case MessageCode.NETWORKCODE_DISABILITYLIST_SUCCESS:
                if (msg.obj != null) {
                    disabilityResultBean = (ObjectResultBean<DisabilityListBean>) msg.obj;
                    if(disabilityResultBean.getData().getList()!=null && disabilityResultBean.getData().getList().size()>0){
                        disabilityBeans.addAll(disabilityResultBean.getData().getList());
                    }
                    kindAdapter.notifyDataSetChanged();
                }

                break;
            case MessageCode.NETWORKCODE_DISABILITYLIST_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;

        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_mianpage);
        patientListDatas = new ArrayList<>();
        initView();
        initData();
        initListener();
        initAllPopup();
        initKindPopup();
    }

    @Override
    protected void initView() {

        ivgLayout = (LinearLayout) findViewById(R.id.mainpage_layout_ivg);

        groupLayout = (LinearLayout) findViewById(R.id.mainpage_layout_group);
        groupTV = (TextView) findViewById(R.id.mainpage_tv_group);
        groupIV = (ImageView) findViewById(R.id.mainpage_iv_group);
        disabilityLayout = (LinearLayout) findViewById(R.id.mainpage_layout_disability);
        disabilityTV = (TextView) findViewById(R.id.mainpage_tv_disability);
        disabilityIV = (ImageView) findViewById(R.id.mainpage_iv_disability);
        timeLayout = (LinearLayout) findViewById(R.id.mainpage_layout_time);
        timeTV = (TextView) findViewById(R.id.mainpage_tv_time);
        timeIV = (ImageView) findViewById(R.id.mainpage_iv_time);

        countTV = (TextView) findViewById(R.id.mainpage_tv_count);


        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.mainpage_swiperefresh);
        expandableListView = (ExpandableListView) findViewById(R.id.mainpage_expandableListView);
        expandableListView.setDividerHeight(0);


        swipeRefreshLayout.setEnabled(true);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setProgressViewOffset(true, -20, 100);

        recyclerView = (RecyclerView) findViewById(R.id.mainpage_recyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
//        adapter = new MainPageListAdapter(this, patientListDatas,this, screenWidth);
//        recyclerView.setAdapter(adapter);

        if (calendarView == null) {
            calendarView = new CalendarClearPopWindow(this);
        }
        calendarView.setCalendarListener(new CalendarClearPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                dateSelected = calendar;
                timeTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
                timeIV.setImageResource(R.mipmap.tab_arrow);
                loading();
                YiJiaHuNetWorkUtils.getDocotrPatientList(groupIdSelected, disabilitySelected, dateSelected, "", handler);

            }
        });

        calendarView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setInitPopup();
            }
        });

    }

    @Override
    protected void initListener() {

        groupLayout.setOnClickListener(this);
        disabilityLayout.setOnClickListener(this);
        timeLayout.setOnClickListener(this);
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
//                Intent intent = new Intent(mContext, MyReportDetailActivity.class);
//                startActivity(intent);
                return true;
            }
        });

    }

    @Override
    protected void initData() {

        //分组数据
        group_list = new ArrayList<DoctorPatientGroupBean>();
        item_list = new ArrayList<List<DoctorPatientBean>>();
        expandAdapter = new MyExpandableListViewAdapter(MainPageActivity.this);
        loading();
        YiJiaHuNetWorkUtils.getDocotrPatientList("","","","",handler);

    }


    private void setInitPopup() {

        groupTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
        groupIV.setImageResource(R.mipmap.tab_arrow);


        disabilityTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
        disabilityIV.setImageResource(R.mipmap.tab_arrow);

        timeTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
        timeIV.setImageResource(R.mipmap.tab_arrow);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mainpage_layout_group:
                allPopup.showAsDropDown(ivgLayout);
                setInitPopup();
                groupTV.setTextColor(mContext.getResources().getColor(R.color.light_blue));
                groupIV.setImageResource(R.mipmap.tab_arrow_pre);

                break;
            case R.id.mainpage_layout_disability:
                kindPopup.showAsDropDown(ivgLayout);
                setInitPopup();
                disabilityTV.setTextColor(mContext.getResources().getColor(R.color.light_blue));
                disabilityIV.setImageResource(R.mipmap.tab_arrow_pre);

                break;
            case R.id.mainpage_layout_time:
                setInitPopup();
                timeTV.setTextColor(mContext.getResources().getColor(R.color.light_blue));
                timeIV.setImageResource(R.mipmap.tab_arrow_pre);
                calendarView.showDropdown(ivgLayout);
                break;
        }
    }


    private void initAllPopup() {
        allPopup = new PopupWindow(this);
        View allView = LayoutInflater.from(this).inflate(R.layout.popup_layout_kind, null);
        allPopup.setContentView(allView);

        allPopup.setWidth(screenWidth);
        allPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        allPopup.setFocusable(true);
        allPopup.setTouchable(true);
        allPopup.setOutsideTouchable(true);
        allPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));


        DoctorGroupDao dao = new DoctorGroupDao(mContext);
        groupBeans = new ArrayList<>();
        DoctorGroupBean bean = new DoctorGroupBean();
        bean.setIsSelect(false);
        bean.setGroupId("");
        bean.setName("全部");
        groupBeans.add(bean);
        groupBeans.addAll(dao.getGroup());
        allListView = (ListView) allView.findViewById(R.id.kind_listview);
        allAdapter = new DoctorGroupAdapter(this, groupBeans);
        allListView.setAdapter(allAdapter);
        //初始化组别
//        for (int i = 0; i < groupBeans.size(); i++) {
//            if (loginInfo.getGroupId().equals(groupBeans.get(i).getGroupId())) {
//                groupBeans.get(i).setIsSelect(true);
//            } else {
//                groupBeans.get(i).setIsSelect(false);
//            }
//        }
//        allAdapter.notifyDataSetChanged();

        allListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i = 0; i < groupBeans.size(); i++) {
                    if (i == position) {
                        groupBeans.get(i).setIsSelect(true);
                    } else {
                        groupBeans.get(i).setIsSelect(false);
                    }
                }

                allAdapter.notifyDataSetChanged();
                groupIdSelected = groupBeans.get(position).getGroupId();
                groupTV.setText(groupBeans.get(position).getName());
                allPopup.dismiss();
                groupTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
                groupIV.setImageResource(R.mipmap.tab_arrow);
                loading();
                YiJiaHuNetWorkUtils.getDocotrPatientList(groupIdSelected, disabilitySelected, dateSelected, "", handler);

            }
        });
        allAdapter.setDisplayListener(new DoctorGroupAdapter.DisplayListener() {
            @Override
            public void onDisplay(int position) {

            }
        });

        allWholeView = (View) allView.findViewById(R.id.kind_view_whole);
        allWholeView.setOnClickListener(this);

        allPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setInitPopup();
            }
        });
    }

    private void initKindPopup() {
        kindPopup = new PopupWindow(this);
        View kindView = LayoutInflater.from(this).inflate(R.layout.popup_layout_kind, null);
        kindPopup.setContentView(kindView);

        kindPopup.setWidth(screenWidth);
        kindPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        kindPopup.setFocusable(true);
        kindPopup.setTouchable(true);
        kindPopup.setOutsideTouchable(true);
        kindPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));


        disabilityBeans = new ArrayList<>();
        DisabilityBean bean = new DisabilityBean();
        bean.setIsSelect(false);
        bean.setName("全部");
        bean.setDisabilityId("");
        disabilityBeans.add(bean);
        kindListView = (ListView) kindView.findViewById(R.id.kind_listview);
        kindAdapter = new DisabilityKindAdapter(this, disabilityBeans);
        kindListView.setAdapter(kindAdapter);
        kindListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                for (int i = 0; i < disabilityBeans.size(); i++) {
                    if (i == position) {
                        disabilityBeans.get(i).setIsSelect(true);
                    } else {
                        disabilityBeans.get(i).setIsSelect(false);
                    }
                }

                kindAdapter.notifyDataSetChanged();
                disabilitySelected = disabilityBeans.get(position).getDisabilityId();
                disabilityTV.setText(disabilityBeans.get(position).getName());
                kindPopup.dismiss();
                disabilityTV.setTextColor(mContext.getResources().getColor(R.color.black_text));
                disabilityIV.setImageResource(R.mipmap.tab_arrow);
                loading();
                YiJiaHuNetWorkUtils.getDocotrPatientList(groupIdSelected, disabilitySelected, dateSelected, "", handler);
            }
        });
        kindAdapter.setDisplayListener(new DisabilityKindAdapter.DisplayListener() {
            @Override
            public void onDisplay(int position) {

            }
        });

        kindWholeView = (View) kindView.findViewById(R.id.kind_view_whole);
        kindWholeView.setOnClickListener(this);

        kindPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setInitPopup();
            }
        });
        YiJiaHuNetWorkUtils.getDisabilityList(loginInfo.getDepartmentId(), handler);
    }


    @Override
    public void onRefresh() {
        loading();
        YiJiaHuNetWorkUtils.getDocotrPatientList("","","","",handler);
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onSelected(String type, int position) {

    }


    //用过ListView的人一定很熟悉，只不过这里是BaseExpandableListAdapter
    class MyExpandableListViewAdapter extends BaseExpandableListAdapter {

        private Context context;

        public MyExpandableListViewAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getGroupCount() {
            return group_list.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return item_list.get(groupPosition).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return group_list.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return item_list.get(groupPosition).get(childPosition);
        }

        public void onGroupCollapsed(int groupPosition) {
            setListViewHeight(expandableListView);
        }

        public void onGroupExpanded(int groupPosition) {
            setListViewHeight(expandableListView);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            GroupHolder groupHolder = null;
            if (convertView == null) {
                convertView = (View) getLayoutInflater().from(context).inflate(
                        R.layout.expendlist_group, null);
                groupHolder = new GroupHolder();
                groupHolder.groupLayout = (LinearLayout) convertView.findViewById(R.id.expandlist_layout_groupitem);
                groupHolder.week = (TextView) convertView.findViewById(R.id.expandlist_tv_week);
                groupHolder.date = (TextView) convertView.findViewById(R.id.expandlist_tv_date);
                groupHolder.patientCount = (TextView) convertView.findViewById(R.id.expandlist_tv_count);
                groupHolder.img = (ImageView) convertView
                 .findViewById(R.id.img);

                convertView.setTag(groupHolder);
            } else {
                groupHolder = (GroupHolder) convertView.getTag();
            }
            groupHolder.week.setText(group_list.get(groupPosition).getWeek());
            groupHolder.date.setText(group_list.get(groupPosition).getDate());
            groupHolder.patientCount.setText(group_list.get(groupPosition).getPatientCount() + "人");
            groupHolder.img.setBackgroundResource(R.mipmap.mainpage_list_arrow_pre);

            if(isExpanded){
                groupHolder.img.setBackgroundResource(R.mipmap.mainpage_list_arrow);
                groupHolder.groupLayout.setBackgroundColor(mContext.getResources().getColor(R.color.expandlist_item_color));
            }else{
                groupHolder.img.setBackgroundResource(R.mipmap.mainpage_list_arrow_pre);
                groupHolder.groupLayout.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            }

            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ItemHolder itemHolder = null;
            if (convertView == null) {
                convertView = (View) getLayoutInflater().from(context).inflate(
                        R.layout.expendlist_item, null);
                itemHolder = new ItemHolder();
                itemHolder.name = (TextView) convertView.findViewById(R.id.expandlistitem_tv_name);
                itemHolder.age = (TextView) convertView.findViewById(R.id.expandlistitem_tv_age);
                itemHolder.sex = (TextView) convertView.findViewById(R.id.expandlistitem_tv_sex);
                itemHolder.disability = (TextView) convertView.findViewById(R.id.expandlistitem_tv_disability);
                itemHolder.userIcon = (CircleImageView) convertView.findViewById(R.id.expandlistitem_iv_img);
                itemHolder.bottomView = (View) convertView.findViewById(R.id.expandlistitem_bottomView);
                convertView.setTag(itemHolder);
            } else {
                itemHolder = (ItemHolder) convertView.getTag();
            }
            itemHolder.name.setText(item_list.get(groupPosition).get(
                    childPosition).getName());
            itemHolder.age.setText(item_list.get(groupPosition).get(
                    childPosition).getAge()+getResources().getString(R.string.usermanger_text_age));
            if("0".equals(item_list.get(groupPosition).get(
                    childPosition).getSex())){
                itemHolder.sex.setText(getResources().getString(R.string.male));
            }else{
                itemHolder.sex.setText(getResources().getString(R.string.female));
            }

            itemHolder.disability.setText(item_list.get(groupPosition).get(
                    childPosition).getDisabilityName());
//            itemHolder.img.setBackgroundResource(item_list2.get(groupPosition).get(
//                    childPosition));

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }

    class GroupHolder {
        public LinearLayout groupLayout;
        public TextView week;
        public TextView date;
        public TextView patientCount;
        public ImageView img;
    }

    class ItemHolder {
        public CircleImageView userIcon;
        public TextView name;
        public TextView age;
        public TextView sex;
        public TextView disability;
        public View bottomView;
    }



    private void setListViewHeight(ExpandableListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        int totalHeight = 0;
        int count = listAdapter.getCount();
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }


}
